<?php

require('pagina.php');
require('database.php');
require('auth.php');
require('core.php');

// Verifica se esta autenticado com pelo menos nivel 2
validaPermissao(2);

// Inicia cabecalho da pagina
pagina_inicio('ParkSys - Shift Reports');
adicionar_css('datechooser.css');
adicionar_js('datechooser.js');
adicionar_js('date-functions.js');
adicionar_js('toggle.js');
adicionar_css('reports.css');
pagina_head();

// Mostra opcoes
echo "<ul id=opcoes>";
echo "<li class='positive'><a href='report_new.php'><img src='img/add.png' alt=''>New Shift Report</a></li>";
echo "<li><a href='reports.php?",
    (isset($_GET['from'])? "&amp;from={$_GET['from']}" : ""),
    (isset($_GET['to'])? "&amp;to={$_GET['to']}" : ""),
    (@$_GET['location']? "&amp;location=" . @$_GET['location'] : ""),
    (isset($_GET['customer'])? "&amp;customer={$_GET['customer']}" : ""),
//		($_GET['manager']? "&amp;manager={$_GET['manager']}" : ""),
    (@$_GET['period']? "&amp;period=" . @$_GET['period'] : ""),
    "&amp;print=1' target='_blank'><img src='img/print.png' alt=''>Print</a></li>";
echo "<li><a href='reports_table.php?",
    (isset($_GET['from'])? "&amp;from={$_GET['from']}" : ""),
    (isset($_GET['to'])? "&amp;to={$_GET['to']}" : ""),
    (@$_GET['location']? "&amp;location=" . @$_GET['location'] : ""),
    (isset($_GET['customer'])? "&amp;customer={$_GET['customer']}" : ""),
//		($_GET['manager']? "&amp;manager={$_GET['manager']}" : ""),
    (@$_GET['period']? "&amp;period=" . @$_GET['period'] : ""),
    "' target='_blank'><img src='img/excel.png' alt=''>Excel Table</a></li>";
echo "</ul><br><br>";

// Mostra reports ainda nao aceitos
$resultado= query_bd("SELECT * FROM reports WHERE state=" . REVIEW . " ORDER BY reportdate, period");

if (!isset($_GET['print']))
{
	echo "<em><a href=\"javascript:toggle('reports_un')\" >Reports to be reviewed(" . mysql_affected_rows() . ")</a></em>";	echo "<table id='reports_un' style='display: none'>";
	echo "<tr><th><th>Date<th>Location/Event<th>Period";

	$mark = False;
	while ($report = mysql_fetch_array($resultado))
	{
			// Verifica se tem permissao para ver todos ou soh os que eh manager
			if (nivelAutenticado() == 2)
			{
				$clocks = query_fetch("SELECT id FROM clocks WHERE report_id={$report['id']} " .
				" AND employee_id={$_SESSION[site_id]['id']} AND manager=TRUE LIMIT 1");
				if (!$clocks)
					continue;
			}

			echo "<tr " . ($mark = !$mark? "class=mark" : "") . ">";
			echo "<td><a href='report.php?id={$report['id']}'><img src='img/report.png' alt='View report details'></a>";
			echo "<td>" . date("D, M d Y", strtotime($report['reportdate']));

			// Busca nome da locacao ou evento
			if ($report['special_event'])
			{
				$evento = query_fetch("SELECT name FROM events WHERE id={$report['location_event_id']}");

				echo "<td>" . (nivelAutenticado() >= 3? "<a href='report.php?id={$report['id']}'>" : "") .
				$evento['name'] .
				(nivelAutenticado() >= 3? "</a>" : "");
			}
			else
			{
				$locacao = query_fetch("SELECT contacts.name, locations.operating FROM locations, contacts" .
					" WHERE locations.id={$report['location_event_id']} AND contacts.id = locations.locationcontact");

				echo "<td>" . (nivelAutenticado() >= 3? "<a href='location.php?id={$report['location_event_id']}'>" : "") .
				$locacao['name'] . ($locacao['operating']? "" : "(not operating)") .
				(nivelAutenticado() >= 3? "</a>" : "");
			}

			//Periodo
			echo "<td>{$PERIOD[$report['period']]}";
			unset($report);
	}
	unset($resultado);
	echo "</table><hr>";
}

// Mostra todos os reports, apenas para administradores
if (nivelAutenticado() >= 3)
{
	// Formulario para entrar com o periodo de tempo
	echo "<form id=periodo method=GET action=reports.php>";
    if (isset($_GET['customer']))
        echo "<input type=HIDDEN name=customer value={$_GET['customer']}>";
	if (isset($_GET['manager']))
		echo "<input type=HIDDEN value='{$_GET['manager']}' name='manager'>";
	if (isset($_GET['location']))
		echo "<input type=HIDDEN value='{$_GET['location']}' name='location'>";
	if (@$_GET['period'] != 0)
		echo "<input type=HIDDEN value='" . @$_GET['period'] . "' name='period'>";
	echo "<label for=from>From:</label> <input id=from type=TEXT value='" . @$_GET['from'] . "' name='from' size=9>",
		"<img class=imgcalendar src='img/calendar.gif' onclick=\"showChooser(this, 'from', 'chooserSpan1', 2000, 2020, Date.patterns.ShortDatePattern, false);\" alt='calendar'>",
		"<div id='chooserSpan1' class='dateChooser select-free' style='display: none; visibility: hidden; width: 160px;'></div>";
	echo "<label for=to>To:</label> <input id=to type=TEXT value='" . @$_GET['to'] . "' name='to' size=9>",
		"<img class=imgcalendar src='img/calendar.gif' onclick=\"showChooser(this, 'to', 'chooserSpan2', 2000, 2020, Date.patterns.ShortDatePattern, false);\" alt='calendar'>",
		"<div id='chooserSpan2' class='dateChooser select-free' style='display: none; visibility: hidden; width: 160px;'></div><br>";
	echo "<input type=CHECKBOX ", (isset($_GET['more'])? "checked=CHECKED" : ""),
		" id=more name=more value=1><label for=more>More information</label> ";
	echo "<label for=period>Period:</label> <select id=period name='period'>";
	echo "<option value=0>Any</option>";
	echo "<option value=", LUNCH, (@$_GET['period'] == LUNCH? " selected=SELECTED" : ""), ">{$PERIOD[LUNCH]}</option>";
	echo "<option value=", DINNER, (@$_GET['period'] == DINNER? " selected=SELECTED" : ""), " >{$PERIOD[DINNER]}</option>";
	echo "<option value=", GRAVEYARD, (@$_GET['period'] == GRAVEYARD? " selected=SELECTED" : ""), ">{$PERIOD[GRAVEYARD]}</option>";
	echo "</select><br>";
		echo "<input type=SUBMIT value='submit' name='ok'><br>";
	echo "</form>";

    /* Include reports table */
    flush();
    echo "<div id=table_container>";
    include('reports_table.php');
    echo "</div>";

	if (isset($_GET['location']))
	{
		$expense =
		query_fetch("SELECT SUM(value) AS expense from duedates WHERE value < 0 AND references_to=" . LOCATION .
			" AND reference_id={$_GET['location']} " .
			($from? " AND UNIX_TIMESTAMP(payday) >= {$from}" : "") .
			($to? " AND UNIX_TIMESTAMP(payday) <= {$to}" : ""));
		$income =
		query_fetch("SELECT SUM(value) AS income from duedates WHERE value > 0 AND references_to=" . LOCATION .
			" AND reference_id={$_GET['location']}" .
			($from? " AND UNIX_TIMESTAMP(payday) >= {$from}" : "") .
			($to? " AND UNIX_TIMESTAMP(payday) <= {$to}" : ""));

		$to = date('Y-m-d', $to);
		$from = date('Y-m-d', $from);

		echo "<ul id=inc_exp_location>";
		echo "<li><strong>Other location <a href='incomes_expenses.php?from={$from}&amp;to={$to}&amp;location={$_GET['location']}'>incomes</a>:</strong> ",
		show_money($income['income']), "</li>";
		echo "<li><strong>Other location <a href='incomes_expenses.php?from={$from}&amp;to={$to}&amp;location={$_GET['location']}'>expenses</a>:</strong> ",
			show_money($expense['expense']), "</li>";
		echo "<li><strong>Location net balance:</strong> ", show_money($total_balance + $income['income'] + $expense['expense']), "</li>";
		echo "<li><strong>Accident Insurance:</strong> ", show_money($total_insurance);

		echo "</li>";
		echo "</ul>";
	}
}

// Finaliza pagina
pagina_fim();
?>
